//
//  HomeTableViewController.swift
//  Weibo
//
//  Created by apple on 15/12/6.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
//原创微博cell的可重用标示符号
 let StatusCellNormaId = "StatusCellNormaId"
//转发微博的可重用cell
let StatusRetweetedCellNormrlId = "StatusRetweetedCellNormrlId"

class HomeTableViewController: VisitorTableViewController {
    ///微博数据列表模型
    private lazy var listViewModel = StatusListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        if !UserAccountViewModel.sharedUserAccount.userLogon{
        
            visitorView?.setuoInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        prepareTableView()
        
        loadData()
        
        
        //注册通知 如果使用 通知中心的block监听 其中的slef 一定要弱引用
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusSelectedPhotoNotification,
            object: nil,
            queue: nil) {[weak self](n) -> Void in

                guard let indexPath = n.userInfo?[WBStatusSelectedPhotoIndexPathKey] as? NSIndexPath else {
                
                    return
                }
                guard let url = n.userInfo?[WBStatusSelectedPhotoURLsKey] as? [NSURL] else {
                
                    return
                }
                
                let vc = PhotoBrowserViewController(urls: url, indexPath: indexPath)
                
                //Modal 展现
                self?.presentViewController(vc, animated: true, completion: nil)
        }
    }
    deinit {
    
        //注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    ///准备表格
    private func prepareTableView() {

        //注册可重用的cell
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellNormaId)
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: StatusRetweetedCellNormrlId)
        
        //去除分隔线
        tableView.separatorStyle = .None
        
        //自动计算行高  需要一个自上而下定的自动布局的控件 制定一个向下的约束
        // 1 首先要设置个约束行高
        tableView.estimatedRowHeight = 400
        
        //下拉刷新
        refreshControl = WBRefreshControl()
        
        //添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        //上拉刷新试图
        tableView.tableFooterView = pullupView
        
//        //测试代码
//        let v = UIView(frame: CGRect(x: 0, y: 0, width: 180, height: 40))
//        v.backgroundColor = UIColor.redColor()
//        refreshControl?.addSubview(v)
        
        //设置tintColor
        refreshControl?.tintColor = UIColor.clearColor()
        
    }

    //加载数据
   @objc private func loadData() {
    
      refreshControl?.beginRefreshing()
    
    listViewModel.loadStatus (isPullup: pullupView.isAnimating()){(isSuccessde) -> () in
            
            //关闭刷新控件 因为在闭包里 所以要用self
            self.refreshControl?.endRefreshing()
            
            //关闭上拉刷新
            self.pullupView.stopAnimating()

            if !isSuccessde {
            
                return
            }
//        print(self.listViewModel.statusList)
            //刷新数据
            self.tableView.reloadData()
    
        }
    }
    //MARK: 懒加载控件
    private lazy var pullupView: UIActivityIndicatorView = {
    
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
        indicator.color = UIColor.lightGrayColor()
        return indicator
    }()
}

//实现数据源的方法

extension HomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //1 获取试图模型
        let vm = listViewModel.statusList[indexPath.row]
        //2 获取可重用的cell 会调用行高的方法
        
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellId, forIndexPath: indexPath) as! StatusCell
        //3 设置试图模型
        
        cell.viewModel = vm
        //4 判断是否是最后一条微博
        if indexPath.row == listViewModel.statusList.count - 1 && !pullupView.isAnimating() {
        
            //开始动画
            pullupView.startAnimating()
            
            //上拉刷新数据
            loadData()
            
            print("上拉刷新数据")
        }
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
     return listViewModel.statusList[indexPath.row].rowHeight
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//        print("选中行\(indexPath)")
    }
}
